package com.luobu.javaee.service;

import com.luobu.javaee.config.JwtConfig;
import com.luobu.javaee.dao.UserMapper;
import com.luobu.javaee.domain.User;
import com.luobu.javaee.email.Mail;
import com.luobu.javaee.email.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.File;

@Service
public class UserService {
    private static final String DEFAULT_HEADER_URL = "DEFAULT_HEADER_URL";
    @Autowired
    UserMapper userMapper;
    @Autowired
    JwtConfig jwtConfig;
    @Autowired
    MailService mailService;

    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    //loadUserByUsername
    public User loadUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    public String login(String username, String password) {
        try {
            User user = this.loadUserByUsername(username);

            System.out.println(user);
            System.out.println(user.getPassword());

            if (user == null) {
                return "User not found";
            }

            // check password
            if (!passwordEncoder.matches(password, user.getPassword())) {
                return "Wrong password";
            }

            // Return the token as the response
            return String.valueOf(user.getId());
        } catch (AuthenticationException e) {
            // Handle authentication failure
            // ...

            return "Login failed";
        }
//        try {
//            if (email != null) {
//                // check code
//                if (mailService.checkCode(email, code)) {
//                    // check if the user exists
//                    User user = this.loadUserByEmail(email);
//                    if (user == null) {
//                        return "User not found";
//                    }
//                    // Return the token as the response
//                    return jwtConfig.generateToken(user.getUsername());
//                } else {
//                    return "Wrong code";
//                }
//            } else if (username != null) {
//                User user = this.loadUserByUsername(username);
//
//                if (user == null) {
//                    return "User not found";
//                }
//
//                // Return the token as the response
//                return jwtConfig.generateToken(user.getUsername());
//            } else {
//                return "Username or email is required";
//            }
//
//        } catch (AuthenticationException e) {
//            // Handle authentication failure
//            // ...
//
//            return "Login failed";
//        }
    }

    private User loadUserByEmail(String email) {
        return userMapper.selectByEmail(email);
    }

    public String register(String username, String password, String email, String code) {
        // check code
        if (mailService.checkCode(email, code)) {
            // check if the user exists
            User user = this.loadUserByEmail(email);
            if (user != null) {
                return "User already exists";
            }
        } else {
            return "Wrong code";
        }
        // Check if the username is already taken
        if (userMapper.selectByUsername(username) != null) {
            return "Username already exists";
        }

        // Create a new User object
        User user = new User();
        user.setUsername(username);

        // Hash the password and set it in the User object
        String hashedPassword = passwordEncoder.encode(password);
        user.setPassword(hashedPassword);
        user.setEmail(email);
        user.setType(0);
        user.setHeaderUrl(DEFAULT_HEADER_URL);

        // Save the User object to the database
        userMapper.save(user);
        // get user id
        user = userMapper.selectByUsername(username);
        // create a folder for the user
        if (user.getId() != null) {
            String workingDirectory = System.getProperty("user.dir");
            String userFolder = workingDirectory + File.separator + user.getId(); // Customize the folder name
            File folder = new File(userFolder);

            if (!folder.exists()) {
                boolean created = folder.mkdirs();
                if (!created) {
                    return "Failed to create folder";
                }
            }
        }

        return login(username, password);
    }

    public String logout(String username) {
        // nothing to do

        return "Logout successful";
    }

    public String email(String email) {
        Mail mail = new Mail();
        mail.setSubject("Luobu Email verification");
        mail.setTo(email);
        int code = mailService.generateCode(email);
        mail.setContent("Your verification code is " + code + ".");
        mailService.sendMail(mail);
        return "Email sent";
    }
}
